import base64
import json
import time
from concurrent.futures import ThreadPoolExecutor

import faker
import requests

# from faker import Faker
# from locust import FastHttpUser, task, run_single_user, constant, tag
from testcases.api_stress import api_stress

index_cookie = 1
fake = faker.Faker()


def get_cookie():
    global index_cookie
    index_cookie += 1
    l = []
    with open('../cookies.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
        return str(l[index_cookie])


def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')


def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str


# class MemoTask(FastHttpUser):
#     host = "https://www.retone-hearing.fit"
#     wait_time = constant(180)
#     # header = {"Content-Type": "application/json"}
#     cookie = get_cookie()
#     # default_headers = {"Content-Type": "application/json"}
#     def on_start(self):
#         numbers_of_user = True
#         if numbers_of_user == True:
#             self.header = {"Cookie": f"hearingaid_user={get_cookie()}",
#                            "Content-Type": "application/json"}
#         else:
#             self.header = {"Cookie": f"hearingaid_user={self.cookie}",
#                            "Content-Type": "application/json"}
#
#     @task
#     @tag('memo_all')
#     def perform(self):
#         # 查询 - 新增 - 删除
#         get_id_url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/getAllMemo'
#         with self.rest('post', get_id_url, headers=self.header) as resp:
#             try:
#                 data = json.loads(decode64_str(resp.js['data']))
#                 self.memoid_list = []
#                 for id in data:
#                     self.memoid_list.append(id['memoId'])
#                 print(len(self.memoid_list))
#                 if len(self.memoid_list) < 10:
#                     url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/addMemo'
#                     data = {
#                         "note": "出门看电影",
#                         "activeTime": "2023-03-01 05:00:00",
#                         "memoTypeEnum": "DAY_OF_WEEK",
#                         "dayOfWeeks": [
#                             "MONDAY",
#                             "WEDNESDAY",
#                             "FRIDAY"
#                         ]
#                     }
#                     for _ in range(10 - len(self.memoid_list)):
#                         with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
#                             if resp.status_code > 400 or (
#                                     resp.json()['data'] == None and resp.json()['description'] != None):
#                                 if resp.json()['description'] == "用户备忘提醒数量超过最大值":
#                                     print('用户备忘提醒数量超过最大值')
#                                     resp.success()
#                                 else:
#                                     resp.failure(f"===错误返回:{resp.json()}===")
#                             else:
#                                 resp.success()
#                 else:
#                     delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
#                     data = {
#                         "memoIdList": self.memoid_list[1:]
#                     }
#                     with self.rest('post', delete_memo, data=enconde_bs64(data), headers=self.header) as resp:
#                         resp.success()
#             except AttributeError:
#                 resp.failure('NoneType error')
#
#
#
#
#
# if __name__ == '__main__':
#     run_single_user(MemoTask)


host = "https://www.retone-hearing.fit"


# print(len(l))

def getall_delall(cookie):
    get_id_url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/getAllMemo'
    header = {"Cookie": f"hearingaid_user={cookie}", "Content-Type": "application/json"}
    with requests.post(host + get_id_url, headers=header, timeout=12) as response:
        # 1 判读请求错误,如果有请求错误,将错误信息返回
        if response.status_code > 400 or (
                response.json()['data'] is None and response.json()['description'] is not None):
            return print(f'请求出错:code={response.status_code}, response={response.json()}')
        else:
            # 2. 如果请求成功, 请求成功的分为有值跟无值,
            data = json.loads(decode64_str(response.json()['data']))
            # 有值需要提取id,无值先跳过
            if len(data) > 0:
                memoid_list = []
                for id in data:
                    memoid_list.append(id['memoId'])
                # 删掉有值全部id
                delete_memo = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/batchDeleteMemo'
                data = {"memoIdList": memoid_list}
                with requests.post(host + delete_memo, data=enconde_bs64(data), headers=header) as response:
                    if response.status_code < 400 or (
                            response.json()['data'] is None and response.json()['description'] is None):
                        print("删除成功")


def add_memo(cookie):
    # 每个用户增加一段备忘提醒, 按每个小时,每个用户每天提醒
    url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/addMemo'
    header = {"Cookie": f"hearingaid_user={cookie}", "Content-Type": "application/json"}
    for i in range(8):
        data = {
            "note": f"今天{i}点出门看电影",
            "activeTime": f"2023-03-01 03:{i*2+40}:00",
            "memoTypeEnum": "EVERY_DAY"
        }
        # print(data)
        with requests.post(host + url, data=enconde_bs64(data), headers=header) as resp:
            # print(resp)
            if resp.status_code > 400 or (resp.json()['data'] is None and resp.json()['description'] is not None):
                print(f'请求出错r{resp.status_code},text = {resp.json()}')


def get_memo_push_log(cookie):
    get_id_url = '/platformRetoneFit/api/memo/needAppUserAuth/responseEncode/requestDecode/getAllMemoPushLog'
    header = {"Cookie": f"hearingaid_user={cookie}", "Content-Type": "application/json"}
    with requests.post(host + get_id_url, headers=header) as resp:
        if resp.status_code > 400 or (resp.json()['data'] == None and resp.json()['description'] != None):
            print(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
        else:
            print(json.loads(decode64_str(resp.json()['data'])))


def run_(func, start=0, end=1):
    """start=0 end=用户数量"""
    username_list = []
    with open('binduser.txt', mode='r', encoding='utf-8') as f:
        for username in f:
            username_list.append(username.strip())
    with ThreadPoolExecutor(100) as t:
        for username in username_list:
            t.submit(api_stress.login, username, 'cc1234')
            # print(task)

    l = []
    with open('cookies.txt', mode='r', encoding='utf8') as f:
        for account in f:
            l.append(account.strip())
    with ThreadPoolExecutor(100) as t:
        # l 列表控制登录用户数量
        for username in l[start:end]:
            future = t.submit(func, username.strip())
    print('over!')

run_(getall_delall, 0, 10)
# run_(add_memo, 5000, 12000)
# run_(get_memo_push_log, 0, 2)
# print(time.time())